<template>
  <div class="index-view">
    

    <!-- 主要内容区域 -->
    <main class="main-content">
      <!-- 英雄区域 -->
      <section class="hero-section">
        <div class="hero-content">
          <div class="hero-text">
              <h1 class="hero-title">涂色抢地盘游戏</h1>
              <p class="hero-subtitle">
                一个简单有趣的多人实时涂色游戏<br>
                通过涂色来占领画布区域，最终占领面积最大的玩家获胜！
              </p>
              <div class="hero-actions">
                <button @click="startQuickGame" class="btn btn-primary btn-large">
                  ⚡ 快速开始
                </button>
                <button @click="showCreateRoom = true" class="btn btn-secondary btn-large">
                  🏠 创建房间
                </button>
                <button @click="showJoinRoom = true" class="btn btn-outline btn-large">
                  🔗 加入房间
                </button>
              </div>
            </div>
            <div class="hero-image">
              <div class="game-preview">
                <canvas ref="previewCanvas" width="400" height="300" class="preview-canvas"></canvas>
                <div class="preview-overlay">
                  <div class="paint-demo">
                    <div class="demo-dot" style="background: #FF6B6B;"></div>
                    <div class="demo-dot" style="background: #4ECDC4;"></div>
                    <div class="demo-dot" style="background: #45B7D1;"></div>
                    <div class="demo-dot" style="background: #96CEB4;"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
      </section>
    </main>

    <!-- 创建房间弹窗 -->
    <div v-if="showCreateRoom" class="modal-overlay" @click="showCreateRoom = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>创建房间</h3>
          <button @click="showCreateRoom = false" class="close-btn">×</button>
        </div>
        <form @submit.prevent="createRoom">
          <div class="form-group">
            <label>房间名称</label>
            <input v-model="roomForm.name" type="text" required maxlength="20" placeholder="输入房间名称">
          </div>
          <div class="form-group">
            <label>最大玩家数</label>
            <select v-model="roomForm.maxPlayers">
              <option v-for="n in [2,3,4,5,6]" :key="n" :value="n">{{ n }}人</option>
            </select>
          </div>
          <div class="form-group">
            <label>游戏时长（分钟）</label>
            <select v-model="roomForm.gameDuration">
              <option value="180">3分钟</option>
              <option value="240">4分钟</option>
              <option value="300">5分钟</option>
            </select>
          </div>
          <div class="form-group">
            <label>房间密码（可选）</label>
            <input v-model="roomForm.password" type="text" maxlength="10" placeholder="留空为公开房间">
          </div>
          <div class="form-actions">
            <button type="button" @click="showCreateRoom = false" class="btn btn-outline">取消</button>
            <button type="submit" class="btn btn-primary" :disabled="creating">
              {{ creating ? '创建中...' : '创建房间' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 加入房间弹窗 -->
    <div v-if="showJoinRoom" class="modal-overlay" @click="showJoinRoom = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>加入房间</h3>
          <button @click="showJoinRoom = false" class="close-btn">×</button>
        </div>
        <form @submit.prevent="joinExistingRoom">
          <div class="form-group">
            <label>房间码</label>
            <input v-model="joinForm.code" type="text" required maxlength="6" placeholder="输入6位房间码" style="text-transform: uppercase;">
          </div>
          <div class="form-group">
            <label>你的昵称</label>
            <input v-model="joinForm.nickName" type="text" required maxlength="15" placeholder="输入你的昵称">
          </div>
          <div class="form-group">
            <label>房间密码（如果有）</label>
            <input v-model="joinForm.password" type="password" maxlength="10" placeholder="输入房间密码">
          </div>
          <div class="form-actions">
            <button type="button" @click="showJoinRoom = false" class="btn btn-outline">取消</button>
            <button type="submit" class="btn btn-primary" :disabled="joining">
              {{ joining ? '加入中...' : '加入房间' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { GameService } from '@/services/gameService'
import { socketService } from '@/services/socketService'
import { API_CONFIG } from '@/config/api'

const router = useRouter()
const previewCanvas = ref(null)
const showCreateRoom = ref(false)
const showJoinRoom = ref(false)
const creating = ref(false)
const joining = ref(false)

// 表单数据
const roomForm = ref({
  name: '',
  maxPlayers: 4,
  gameDuration: 180,
  password: ''
})

const joinForm = ref({
  code: '',
  nickName: '',
  password: ''
})





// 方法
const startQuickGame = async () => {
  try {
    const game = await GameService.createGame({
      name: `快速游戏 ${Date.now()}`,
      maxPlayers: 4,
      gameDuration: 180
    })
    router.push(`/game/${game.code}`)
  } catch (error) {
    console.error('快速开始失败:', error)
    alert('快速开始失败，请重试')
  }
}

const createRoom = async () => {
  creating.value = true
  try {
    const game = await GameService.createGame(roomForm.value)
    showCreateRoom.value = false
    router.push(`/game/${game.code}`)
  } catch (error) {
    console.error('创建房间失败:', error)
    alert('创建房间失败，请重试')
  } finally {
    creating.value = false
  }
}

const joinExistingRoom = async () => {
  joining.value = true
  try {
    const game = await GameService.joinGame(
      joinForm.value.code.toUpperCase(),
      joinForm.value.nickName,
      joinForm.value.password || null
    )
    showJoinRoom.value = false
    router.push(`/game/${game.code}`)
  } catch (error) {
    console.error('加入房间失败:', error)
    alert('加入房间失败，请检查房间码和昵称')
  } finally {
    joining.value = false
  }
}

const joinGame = (code) => {
  joinForm.value.code = code
  showJoinRoom.value = true
}



// 初始化预览画布
const initPreviewCanvas = () => {
  const canvas = previewCanvas.value
  if (!canvas) return
  
  const ctx = canvas.getContext('2d')
  const colors = API_CONFIG.GAME.PLAYER_COLORS
  
  // 绘制背景
  ctx.fillStyle = '#f8f9fa'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  
  // 绘制示例涂色
  colors.slice(0, 4).forEach((color, index) => {
    ctx.fillStyle = color
    const x = (index % 2) * 200 + 50
    const y = Math.floor(index / 2) * 150 + 50
    ctx.beginPath()
    ctx.arc(x, y, 30, 0, Math.PI * 2)
    ctx.fill()
  })
}

onMounted(() => {
  initPreviewCanvas()
})
</script>

<style scoped>
.index-view {
  min-height: 100vh;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

.main-content {
  flex: 1;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  min-height: 0;
  margin: 0;
  padding: 0;
}

.hero-section {
  width: 100vw;
  max-width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  min-height: 0;
  margin: 0;
  padding: 0;
}

.hero-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
  align-items: center;
  width: 100%;
  max-width: 100%;
  margin: 0;
  padding: 2rem;
  box-sizing: border-box;
}

.hero-title {
  font-size: 3rem;
  color: white;
  margin-bottom: 1rem;
  font-weight: bold;
}

.hero-subtitle {
  font-size: 1.3rem;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 2rem;
  line-height: 1.6;
}

.hero-actions {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.btn {
  padding: 1rem 2rem;
  border: none;
  border-radius: 0.5rem;
  font-size: 1.1rem;
  cursor: pointer;
  transition: all 0.3s;
  text-decoration: none;
  display: inline-block;
  text-align: center;
}

.btn-primary {
  background: #4CAF50;
  color: white;
}

.btn-secondary {
  background: #2196F3;
  color: white;
}

.btn-outline {
  background: transparent;
  color: white;
  border: 2px solid white;
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.hero-image {
  display: flex;
  justify-content: center;
  align-items: center;
}

.game-preview {
  position: relative;
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.preview-canvas {
  border: 1px solid #ddd;
  border-radius: 0.5rem;
}

.section-title {
  text-align: center;
  font-size: 2.5rem;
  color: white;
  margin-bottom: 3rem;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 1rem;
  padding: 2rem;
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: bold;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 0.5rem;
  font-size: 1rem;
}

.form-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
}

.btn-sm {
  padding: 0.5rem 1rem;
  font-size: 0.9rem;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .hero-content {
    grid-template-columns: 1fr;
    text-align: center;
  }
  
  .hero-title {
    font-size: 2rem;
  }
  
  .hero-actions {
    justify-content: center;
  }
  

}
</style>